package com.coder4j;

import com.coder4j.biz.entity.WechatLinkEntity;
import com.coder4j.starter.tools.util.DateUtils;
import org.junit.jupiter.api.Test;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

public class ATest {
    @Test
    public void a() throws Exception{
        String url = "https://mp.weixin.qq.com/s/pkOFXELWGWpQ3w0ZTNBrEQ?token=1699568153&lang=zh_CN";
        // 连接到URL并获取HTML文档
        Document document = Jsoup.connect(url).get();

        // 获取所有的meta标签
        Elements metaTags = document.select("meta");

        WechatLinkEntity entity = new WechatLinkEntity();

        // 遍历meta标签并打印其属性
        for (Element metaTag : metaTags) {
            String property = metaTag.attr("property");
            String content = metaTag.attr("content");
            System.out.println("property: " + property + ", Content: " + content);
            switch (property){
                case "og:title":{
                    entity.setTitle(content);
                }break;
                case "og:url":{
                    entity.setLink(content);
                }break;
                case "og:image":{
                    entity.setImg(content);
                }break;
                default:break;
            }
        }
        if(entity.getImg() != null){
            downloadImage(entity.getImg());
        }
    }
    private void downloadImage(String imgUrl) throws Exception {
        URL url = new URL(imgUrl);
        String fileName = DateUtils.getTimeMask()+".jpg";
        String ste = "D:\\Projects\\my\\my-spring-helper\\keller-server\\src\\main\\resources\\";
        File destination = new File(ste + fileName);

        Files.copy(url.openStream(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
        System.out.println("Downloaded image: " + destination.getAbsolutePath());
    }
}
